package net.zjitc.controller;

import net.zjitc.pojo.CartItem;
import net.zjitc.pojo.Product;
import net.zjitc.pojo.User;
import net.zjitc.service.CartService;
import net.zjitc.service.impl.CartServiceImpl;
import net.zjitc.utils.dispacher.URLMapping;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/11.
 */
public class UserCart {
    CartService cartService = new CartServiceImpl();
    @URLMapping(url = "/findMyCart")
    public String findMyCart(HttpServletRequest request, HttpServletResponse response){

        //查询谁的购物车？？当前用户
     /*  User user = (User) request.getSession().getAttribute("user");

        if (user == null){
            return "/WEB-INF/user/cart.jsp";
        } */
        List<CartItem> list = cartService.findByUid(1);
        request.setAttribute("list",list);

        double total = 0.0;
        for (CartItem c: list){
             total = total+c.getQuantity()*c.getProduct().getShop_price();
        }
        request.setAttribute("total",total);
        return "/WEB-INF/user/cart.jsp";
    }
    @URLMapping(url = "/addCart")
    public String addCart(HttpServletRequest request, HttpServletResponse response){

        //判断用户是否登录
        Map<String, String[]> map = request.getParameterMap();
        //将接收的参数的参数封成对象  pid quantity  cartItem里面没有pid，pid在product

        CartItem cartItem = new CartItem();
        Product product = new Product();
        try {
            User user = new User();
            user.setUid(1);
            BeanUtils.populate(cartItem,map);
            BeanUtils.populate(product,map);
            cartItem.setUser(user);
            cartItem.setProduct(product);
            int count = cartService.add(cartItem);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //添加完后，要重定向到。。。。。
        String url = request.getContextPath()+"/findMyCart";
        return "Redirect:"+url ;
    }

}
